/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.cbm.smsbroadcast;

import com.elcom.emocbc.util.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class SmsBroadcaster implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final byte[] binaryArray;
    private final Integer msgId;
    private final String[] msisdnList;

    public SmsBroadcaster(byte[] binaryArray, Integer msgId, String[] msisdnList) {
        this.binaryArray = binaryArray;
        this.msgId = msgId;
        this.msisdnList = msisdnList;
    }

    @Override
    public void run() {
        ConfigurationManager.reloadConfiguration();

        if (msisdnList != null && msisdnList.length > 0) {
            SmppClient smppClient = SmppClient.getInstance();
            String shortCode = ConfigurationManager.getStrProp("cell_broadcast", "SmsBroadcast.shortCode", "9220");
            byte[][] smsChunks = getSmsChunks(binaryArray, msgId);
            for (String msisdn : msisdnList) {
                if (SmsBroadcastConfig.smsBroadcastEnable(msisdn)) {
                    for (byte[] smsChunk : smsChunks) {
                        smppClient.send(shortCode, msisdn, smsChunk);
                        logger.debug("[SmsBroadcaster] Sent sms broadcast to {}: {}", msisdn, smsChunk);
                    }
                }
            }
        }
    }

    private byte[][] getSmsChunks(byte[] binaryArray, Integer msgId) {
        return TestSmsAsCB2.split(binaryArray, msgId);
    }

}
